<template>
  <PageContainer>
    <view class="container">
      <Header title="申请秘书处撮合">
        <CustomTopTips :text="topTips" />
      </Header>
      <view class="bg-white br-16 overflow-hidden ma-16">
        <BasicsForm @register="register" @reset="onReset" @submit="onSubmit" />
      </view>

      <view class="mx-16 mb-16">
        <UniForms :modelValue="formData" ref="formRef">
          <view class="p-12 bgf mt-12 br-8">
            <UniFormsItem label="撮合激励" :contentRight="true" name="incentiveOpen">
              <FormSwitch v-model="incentiveOpen"></FormSwitch>
            </UniFormsItem>

            <template v-if="formData.incentiveOpen">
              <view class="fz-14 linh-20 mb-22" style="color: #999996">
                注：仅供秘书处成员可见，无需线上支付，具体激励情况以及结算方式由线下再自由处理。
              </view>

              <UniFormsItem label="" name="incentiveType" labelPosition="top">
                <FormDataCheckbox
                  v-model.number="formData.incentiveType"
                  :localdata="[
                    {
                      value: IncentiveTypeEnum.Commission,
                      text: '佣金激励',
                    },
                    {
                      value: IncentiveTypeEnum.Other,
                      text: '其它激励',
                    },
                  ]"
                ></FormDataCheckbox>
              </UniFormsItem>

              <UniFormsItem
                v-if="formData.incentiveType === IncentiveTypeEnum.Commission"
                label="预估规模"
                labelWidth="100"
                :contentRight="true"
                :required="true"
                name="estimatedScale"
                :rules="[
                  {
                    required: true,
                    errorMessage: '请填写预估规模',
                  },
                ]"
              >
                <!-- <EstimatedScale v-model="formData.estimatedScale"></EstimatedScale> -->
                <view
                  class="disFlxAC br-4 pr-16 pl-6 py-4"
                  style="background-color: #f2f3f5; width: 240rpx"
                >
                  <FormInput v-model.number="formData.estimatedScale" :input-border="false" />
                  <text>元</text>
                </view>
              </UniFormsItem>

              <UniFormsItem
                v-if="formData.incentiveType == IncentiveTypeEnum.Commission"
                label="成交佣金比例"
                name="incentiveCommissionRate"
                :contentRight="true"
                labelWidth="100"
                :required="true"
                :rules="[
                  {
                    required: true,
                    errorMessage: '请填写佣金比例',
                  },
                ]"
              >
                <view
                  class="disFlxAC br-4 pr-16 pl-6 py-4"
                  style="background-color: #f2f3f5; width: 240rpx"
                >
                  <FormInput
                    v-model.number="formData.incentiveCommissionRate"
                    :input-border="false"
                  />
                  <text>%</text>
                </view>
              </UniFormsItem>

              <UniFormsItem
                v-if="formData.incentiveType == IncentiveTypeEnum.Other"
                label="激励说明"
                name="incentiveDetails"
                labelPosition="top"
                :required="false"
                :rules="[
                  {
                    required: false,
                    errorMessage: '请填写激励说明',
                  },
                ]"
              >
                <view class="pa-8" style="background-color: #f2f3f5">
                  <FormInput
                    v-model="formData.incentiveDetails"
                    :input-border="false"
                    :maxlength="60"
                    type="textarea"
                    placeholder="例如：赠送本店一次xx项目免费体验等"
                    :autoHeight="true"
                    :styles="{
                      height: '160rpx',
                      backgroundColor: 'transparent',
                    }"
                  />
                </view>
              </UniFormsItem>
            </template>
          </view>
        </UniForms>
      </view>
      <view style="height: 176rpx"></view>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* requestAdminMatch 申请秘书处撮合 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import CustomTopTips from '@/components/CustomTopTips/index.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm } from '@/components/Form';
  import { isArray, isBoolean } from 'lodash-es';
  import type { ApplyCooperation } from '@/router/types/modules';
  import { computed, reactive, ref } from 'vue';
  import { navigateBack, onLoad, reLaunch } from '@/router';
  import UniForms from '@/components/Form/uni_modules/uni-forms/uni-forms.vue';
  import UniFormsItem from '@/components/Form/uni_modules/uni-forms-item/uni-forms-item.vue';
  import FormDataCheckbox from '@/components/Form/components/FormDataCheckbox.vue';
  import FormInput from '@/components/Form/components/FormInput.vue';
  import FormSwitch from '@/components/Form/components/FormSwitch.vue';
  import type { SubmitAnswerListItem } from '@/api/membership/formCompTypes';
  import { onUnload } from '@dcloudio/uni-app';
  import { SupplyDemandFormAnswerCacheKey } from '../../components/utils';
  import {
    ApplicationTypeEnum,
    IncentiveOpenEnum,
    IncentiveTypeEnum,
  } from '@/enums/businessOpportunitiesEnum';
  import { supplyDemandFormSubmit } from '@/api/businessOpportunities';
  import type { CardBottomBtnsOptions } from '@/components/TButtonGroup/types';

  const routeOptions = ref<ApplyCooperation>();

  const btnGroupOptions = ref<CardBottomBtnsOptions>({
    placeholder: false,
    styles: {
      backgroundColor: '#fff',
    },
    reset: {
      text: '上一步',
      customClass: 'borderBtn',
      customStyle: {
        borderRadius: '44rpx',
      },
    },
    submit: {
      text: '提交',
      customStyle: {
        backgroundColor: '#2878FF',
        color: '#fff',
        borderRadius: '44rpx',
      },
    },
  });

  const [register, {}] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    validateTrigger: 'bind',
    btnGroupOptions,
    schemas: [
      {
        field: 'boIntention',
        label: '合作申请留言',
        component: 'InputTextArea',
        required: true,
        componentProps: {
          placeholder: '给秘书处说说您的需求吧~',
          maxlength: 100,
        },
      },
      {
        field: 'boContact',
        label: '您的联系方式是？',
        required: true,
        component: 'InputTextArea',
        componentProps: {
          placeholder: '输入您的联系方式，例如：手机号152****5678',
          maxlength: 100,
        },
      },
    ],
  });

  const topTips = ref<string>(
    '如果已提交合作意向，申请撮合将会把您提交的合作意向信息同步给秘书处管理员看，请知悉。',
  );
  onLoad<'requestAdminMatch'>((op) => {
    if (isBoolean(op.isIntendedRecipient)) {
      btnGroupOptions.value.reset = void 0;
      btnGroupOptions.value.submit!.text = '发送撮合申请';
    }
    routeOptions.value = op;
    if (uni.getStorageSync(SupplyDemandFormAnswerCacheKey)) {
      topTips.value = '秘书处同意撮合后，才会把合作意向发送给供需发布者查看。';
    }
  });

  const formData = reactive({
    incentiveOpen: IncentiveOpenEnum.No,
    incentiveType: IncentiveTypeEnum.Commission,
    incentiveDetails: '',
    estimatedScale: '',
    incentiveCommissionRate: void 0,
  });
  const formRef = ref<InstanceType<typeof UniForms>>();

  const incentiveOpen = computed({
    get() {
      return !!formData.incentiveOpen;
    },
    set(val) {
      formData.incentiveOpen = val ? 1 : 0;
    },
  });

  let isPreviousStep = false;
  /** 上一步 */
  function onReset() {
    isPreviousStep = true;
    navigateBack();
  }

  async function onSubmit(vals: Recordable<string>) {
    if (!routeOptions.value) return;
    await formRef.value?.validate();

    const answerCache = uni.getStorageSync(
      SupplyDemandFormAnswerCacheKey,
    ) as SubmitAnswerListItem[];
    let data: any = {
      boContactType: ApplicationTypeEnum.match,
      shareKey: routeOptions.value.shareKey,
      incentiveOpen: formData.incentiveOpen,
      boIntention: vals['boIntention'],
      boContact: vals['boContact'],
      customFormItem: {},
    };
    /** 从供需(供需)详情发起申请, 提交供需ID */
    if (routeOptions.value.id) {
      data.boInfoId = routeOptions.value.id;
    }
    /** 从意向详情发起申请, 提交意向ID */
    if (routeOptions.value.boUserApplyRecordId) {
      data.boUserApplyRecordId = routeOptions.value.boUserApplyRecordId;
    }
    if (answerCache && isArray(answerCache)) {
      data.customFormItem = {
        customFormId: routeOptions.value.id,
        answerList: answerCache,
      };
    }
    if (data.incentiveOpen === IncentiveOpenEnum.Yes) {
      if (formData.incentiveType === IncentiveTypeEnum.Commission) {
        data = {
          incentiveType: formData.incentiveType,
          incentiveCommissionRate: formData.incentiveCommissionRate,
          estimatedScale: formData.estimatedScale,
          ...data,
        };
      } else {
        data = {
          incentiveType: formData.incentiveType,
          incentiveDetails: formData.incentiveDetails,
          ...data,
        };
      }
    }
    const res = await supplyDemandFormSubmit(data, routeOptions.value.isIntendedRecipient);

    reLaunch({
      name: 'applyCooperationResult',
      options: {
        id: res.id,
        type: ApplicationTypeEnum.match,
        boInfoId: routeOptions.value.id!,
        isIntendedRecipient: routeOptions.value.isIntendedRecipient,
        auditRecordId: res.auditRecordId
      },
    });
  }

  onUnload(() => {
    if (!isPreviousStep) uni.removeStorageSync(SupplyDemandFormAnswerCacheKey);
  });
</script>

<style lang="scss" scoped></style>
